package com.wfyn.reggie.modules.sys.controller;

import com.wfyn.reggie.common.web.base.BaseController;
import com.wfyn.reggie.common.web.domain.Result;
import com.wfyn.reggie.modules.sms.utils.ValidateCodeUtils;
import com.wfyn.reggie.modules.sys.domain.User;
import com.wfyn.reggie.modules.sys.service.UserService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 用户管理
 * @author wfyn
 * @date 2023/9/30
 */

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    UserService userService;

    @PostMapping("/sendMsg")
    public Result sendMsg(@RequestBody User user, HttpSession session) {

        String phone = user.getPhone();
        if (StringUtils.isNotEmpty(phone)) {
            String code = ValidateCodeUtils.generateValidateCode(4).toString();

            log.info("验证码为:{}  ", code);

            session.setAttribute(phone, code);
            return success("短信发送成功");

        }

        return failure("短信发送失败");
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpSession session) {

        String phone = user.getPhone();
        String code = user.getCode();
        log.info(" {},{}",phone,code);
        if (StringUtils.isNotEmpty(phone) && StringUtils.isNotEmpty(code)) {
            String sessionCode = (String) session.getAttribute(phone);
            log.info("验证码校验：{}",sessionCode);
            if (StringUtils.isNotEmpty(sessionCode) && sessionCode.equals(code)) {
                User user1 = userService.getUserByPhone(phone);
                if (user1 != null) {
                    session.setAttribute("user", user1.getId());

                }
                else {
                    userService.save(user);
                    session.setAttribute("user", user.getId());
                }
                return success("登陆成功");


            }
            return failure("验证码不对");
        }
        return failure("用户名或验证码为空");
    }
}

